---
title: "Reference: MongoDB Vector Store | Vector Databases | RAG | Kastrax Docs"
description: Documentation for the MongoDBVector class in Kastrax, which provides vector search using MongoDB Atlas and Atlas Vector Search.
---

# MongoDB Vector Store ✅

The `MongoDBVector` class provides vector search using [MongoDB Atlas Vector Search](https://www.mongodb.com/docs/atlas/atlas-vector-search/). It enables efficient similarity search and metadata filtering within your MongoDB collections.

## Installation ✅

```bash copy
npm install @kastrax/mongodb
```

## Usage Example ✅

```typescript copy showLineNumbers
import { MongoDBVector } from '@kastrax/mongodb';

const store = new MongoDBVector({
  url: process.env.MONGODB_URL,
  database: process.env.MONGODB_DATABASE,
});
```

## Constructor Options ✅

<PropertiesTable
  content={[
    {
      name: "url",
      type: "string",
      description: "MongoDB connection string (URI)",
    },
    {
      name: "database",
      type: "string",
      description: "Name of the MongoDB database to use",
    },
    {
      name: "options",
      type: "MongoClientOptions",
      isOptional: true,
      description: "Optional MongoDB client options",
    },
  ]}
/>

## Methods ✅

### createIndex()

Creates a new vector index (collection) in MongoDB.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection to create (see naming rules below)",
    },
    {
      name: "dimension",
      type: "number",
      description: "Vector dimension (must match your embedding model)",
    },
    {
      name: "metric",
      type: "'cosine' | 'euclidean' | 'dotproduct'",
      isOptional: true,
      defaultValue: "cosine",
      description: "Distance metric for similarity search",
    },
  ]}
/>

### upsert()

Adds or updates vectors and their metadata in the collection.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection to insert into",
    },
    {
      name: "vectors",
      type: "number[][]",
      description: "Array of embedding vectors",
    },
    {
      name: "metadata",
      type: "Record<string, any>[]",
      isOptional: true,
      description: "Metadata for each vector",
    },
    {
      name: "ids",
      type: "string[]",
      isOptional: true,
      description: "Optional vector IDs (auto-generated if not provided)",
    },
  ]}
/>

### query()

Searches for similar vectors with optional metadata filtering.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection to search in",
    },
    {
      name: "queryVector",
      type: "number[]",
      description: "Query vector to find similar vectors for",
    },
    {
      name: "topK",
      type: "number",
      isOptional: true,
      defaultValue: "10",
      description: "Number of results to return",
    },
    {
      name: "filter",
      type: "Record<string, any>",
      isOptional: true,
      description: "Metadata filters (applies to the `metadata` field)",
    },
    {
      name: "documentFilter",
      type: "Record<string, any>",
      isOptional: true,
      description: "Filters on original document fields (not just metadata)",
    },
    {
      name: "includeVector",
      type: "boolean",
      isOptional: true,
      defaultValue: "false",
      description: "Whether to include vector data in results",
    },
    {
      name: "minScore",
      type: "number",
      isOptional: true,
      defaultValue: "0",
      description: "Minimum similarity score threshold",
    },
  ]}
/>

### describeIndex()

Returns information about the index (collection).

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection to describe",
    },
  ]}
/>

Returns:

```typescript copy
interface IndexStats {
  dimension: number;
  count: number;
  metric: "cosine" | "euclidean" | "dotproduct";
}
```

### deleteIndex()

Deletes a collection and all its data.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection to delete",
    },
  ]}
/>

### listIndexes()

Lists all vector collections in the MongoDB database.

Returns: `Promise<string[]>`

### updateIndexById()

Updates a specific vector entry by its ID with new vector data and/or metadata.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection containing the vector",
    },
    {
      name: "id",
      type: "string",
      description: "ID of the vector entry to update",
    },
    {
      name: "update",
      type: "object",
      description: "Update data containing vector and/or metadata",
    },
    {
      name: "update.vector",
      type: "number[]",
      isOptional: true,
      description: "New vector data to update",
    },
    {
      name: "update.metadata",
      type: "Record<string, any>",
      isOptional: true,
      description: "New metadata to update",
    },
  ]}
/>

### deleteIndexById()

Deletes a specific vector entry from an index by its ID.

<PropertiesTable
  content={[
    {
      name: "indexName",
      type: "string",
      description: "Name of the collection containing the vector",
    },
    {
      name: "id",
      type: "string",
      description: "ID of the vector entry to delete",
    },
  ]}
/>

### disconnect()

Closes the MongoDB client connection. Should be called when done using the store.

## Response Types ✅

Query results are returned in this format:

```typescript copy
interface QueryResult {
  id: string;
  score: number;
  metadata: Record<string, any>;
  vector?: number[]; // Only included if includeVector is true
}
```

## Error Handling ✅

The store throws typed errors that can be caught:

```typescript copy
try {
  await store.query({
    indexName: "my_collection",
    queryVector: queryVector,
  });
} catch (error) {
  // Handle specific error cases
  if (error.message.includes("Invalid collection name")) {
    console.error(
      "Collection name must start with a letter or underscore and contain only valid characters."
    );
  } else if (error.message.includes("Collection not found")) {
    console.error("The specified collection does not exist");
  } else {
    console.error("Vector store error:", error.message);
  }
}
```

## Best Practices ✅

- Index metadata fields used in filters for optimal query performance.
- Use consistent field naming in metadata to avoid unexpected query results.
- Regularly monitor index and collection statistics to ensure efficient search.

## Related ✅

- [Metadata Filters](./metadata-filters)
